package com.huan.vertxle.initialization;

import com.huan.vertxle.model.ConfigParams;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.pgclient.PgConnectOptions;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.PoolOptions;

/**
 * @author huan
 */
public class PgSqlInit {
  private final InternalLogger logger = Slf4JLoggerFactory.getInstance(this.getClass());

  public static PgPool client;

  public void init() {
    cretePgSqlClient().onSuccess(pgPool -> {
      client = pgPool;
      logger.info("postgre 初始化成功");
    }).onFailure(throwable -> {
      logger.error("postgre初始化失败:{}", throwable.getMessage());
      Vertx.currentContext().owner().close();
    });
  }

  private Future<PgPool> cretePgSqlClient() {
    Promise<PgPool> promise = Promise.promise();
    ConfigParams.PgSqlTO postgre = StartParamsInit.init.getPostgre();
    PgConnectOptions connectOptions = new PgConnectOptions().setPort(postgre.getPort()).setHost(postgre.getHost())
        .setDatabase(postgre.getDatabase()).setUser(postgre.getUser()).setPassword(postgre.getPassword());
    PoolOptions poolOptions = new PoolOptions().setMaxSize(5);
    client = PgPool.pool(Vertx.currentContext().owner(), connectOptions, poolOptions);
    // 测试连接是否接通
    client.query("select 1").execute().onSuccess(event -> promise.complete(client)).onFailure(promise::fail);
    return promise.future();
  }
}
